// pages/accounting_period/accounting_period.js
let listBehavior = require('../../behavior/list')

Page({
  behaviors: [ listBehavior, ],
  /**
   * 页面的初始数据
   */
  data: {
    auth: {},
    // list: [],                 // 列表
    // total: 0,
    // page: 1,
    // limit: 30,
    // scrollReset: false,

    searchList: [
      { field_name: '会计期', type: 'reference1', field_id: ['account_period_s', 'account_period_e'], optionList: [], optionId: 'account_period', optionName: 'account_period', },
      { field_name: '状态', type: 'reference1', field_id: 'account_state', optionList: [
        { id: '完结', name: '完结', },
        { id: '处理', name: '处理', },
      ], optionId: 'id', optionName: 'name', },
    ],
    quickFlag: false,
    accountVal: '',

    // 弹窗
    diaShow: false,
    diaTitle: '',
    diaContent: '',
    isNeedCheck: false,
    checked: false,
    selectedItem: {},
    // 状态弹窗还是结转标识弹窗
    isEditState: false,
  },

  toggleFlag(e) {
    this.setData({
      quickFlag: !this.data.quickFlag,
    })
  },
  searchQuick(e) {
    let obj = e.detail,
        query = {},
        abstract = this.query.abstract
    Object.values(obj).forEach(item => {
      let { field_id, val, } = item
      if(Array.isArray(field_id)) {
        val.forEach((v, i) => {
          if(![undefined, null, '',].includes(v)) query[field_id[i]] = v
        })
      } else if(![undefined, null, '',].includes(val)) {
        query[field_id] = val
      }
    })
    this.query = query
    if(abstract) this.query.abstract = abstract
    let arr = []
    if(query.account_period_s) arr.push(query.account_period_s)
    if(query.account_period_e) arr.push(query.account_period_e)
    this.setData({
      accountVal: arr.join(' - '),
    })
    this.getFirstPage()
  },

  // 状态开关
  onStateSwitchChange(e) {
    let { item, i, } = e.currentTarget.dataset,
        val = e.detail,
        name = item.account_state === '处理' ? '完结' : '处理',
        title = '修改状态',
        content = name === '处理' ? '确定修改该会计期状态为处理？' : '确定修改该会计期状态为完结？'
    this.showDia(item, i, title, content, false, true)
  },
  // 标识开关
  onFlagSwitchChange(e) {
    let { item, i, } = e.currentTarget.dataset,
        { is_charges, } = item
    if(is_charges) { // 取消结转
      // this.carryForward(true, post, i)
      this.showDia(item, i, '反结转会计期', '确定反结转该会计期？', false)
    } else {  // 结转
      let userLevel = wx.getStorageSync('userLevel'),
          isNeedCheck = userLevel == '1'  // 平台人员增加勾选是否覆盖未结算的会计期报表格式
      this.showDia(item, i, '结转会计期', '确定结转该会计期？', isNeedCheck)
    }
  },
  showDia(item, i, title, content, isNeedCheck, isEditState) {
    this.data.selectedItem = { ...item, i, }
    this.data.isEditState = isEditState || false
    this.setData({
      diaShow: true,
      diaTitle: title,
      diaContent: content,
      isNeedCheck,
    })
  },
  // 弹窗 结转会计期弹窗确认
  onDiaConfirm(e) {
    let { isEditState, selectedItem, isNeedCheck, checked, auth, } = this.data,
        { account_period, i, is_charges, account_state, } = selectedItem,
        post = {
          account_period,
        }
    if(isEditState) { // 状态修改
      console.log('状态修改', auth.tableEdit, );
      if(!auth.tableEdit || !auth.fieldEdit.includes('account_state')) {
        wx.$toast('抱歉，您没有权限修改会计期状态')
        return
      }
      let name = account_state === '处理' ? '完结' : '处理'
      post.account_state = name
      this.editPeriodState(post, i)
    } else { // 结转标识修改
      if(!auth.tableEdit || !auth.fieldEdit.includes('is_charges')) {
        wx.$toast('抱歉，您没有权限修改会计期结转状态')
        return
      }
      if(is_charges) { // 取消结转
        post.is_overwrite = false
        this.carryForward(true, post, i)
      } else {  // 结转
        if(isNeedCheck) post.is_overwrite = checked
        this.carryForward(false, post, i)
      }
    }
  },
  onCheckChange(e) {
    this.setData({
      checked: e.detail,
    })
  },

  // 接口
  ready() {
    this.query = {}

    // 获取会计期
    wx.$post(3, 'Account/query_all_account_period', { limit: 0, page: 1, }).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row,
          searchList = this.data.searchList
      searchList[0].optionList = rows
      this.setData({
        searchList,
      })
    })
  },
  getDataList() {
    if(!this.data.auth.tableSee) {
      let { total, page, limit, } = this.data
      wx.$toast('抱歉，您没有权限查看该模块')
      this.setData({
        total,
        page,
        limit,
      })
      return
    }

    let { page, limit, list, } = this.data
    let post = {
      page,
      limit,
      ...this.query,
    }
    wx.$post(3, 'Account/query_all_account_period', post).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row
      if(page !== 1) rows = [ ...list, ...rows, ]
      this.setData({
        list: rows,
        total: res.data.total,
        // total: 0,
        page,
      })
    })
  },
  // 处理/完结
  editPeriodState(post, idx) {
    wx.showLoading({ mask: true, })
    wx.$post(3, 'Account/alter_all_account_period', post).then(res => {
      if(res.errcode !== 0) return
      wx.$toast('修改成功')
      // 成功后，重新请求该条数据
      this.getRowData(post.account_period, idx)
    })
  },
  // 结转/反结转
 /* carryForward(isCancel, post, idx) {
    let url = isCancel ? 'Account/cancel_charges_all_account_summary' : 'Account/charges_all_account_summary'
    wx.$post(3, url, post).then(res => {
      if(res.errcode !== 0) return
      wx.$toast(isCancel ? '反结转成功！' : '结转成功！')
      // 成功后，重新请求该条数据
      this.getRowData(post.account_period, idx)
    })
  },*/
  // 221104 liang 按pc更新，改用v2接口
  // 结转/反结转
 /* carryForward(isCancel, post, idx) {
    let url = isCancel ? 'Account/cancel_charges_all_account_summary_v2' : 'Account/charges_all_account_summary_v2'
    post.period = post.account_period
    delete post.account_period
    post.guid = this.GetGUID()
    wx.showLoading({ mask: true, })
    wx.$post(3, url, post, true, true).then(res => {
      // res 返回值是 null，不做处理

    })
    let pre_setTime = setInterval(() => {
      wx.$post(6, `ImportExcel/GetCacheProgress?guid=${post.guid}`, {}).then(res => {
        if(res.State == 3 || res.ImportProgress >= 100) {
          wx.$toast(isCancel ? '反结转成功！' : '结转成功！')
          // 成功后，重新请求该条数据
          this.getRowData(post.period, idx)
          clearInterval(pre_setTime)
        }
      })
    }, 500)
  },*/
  GetGUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      let r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
  },
  getRowData(account_period, idx) {
    // let post = {
    //   account_period_s: account_period,
    //   account_period_e: account_period,
    // }
    let list = this.data.list,
        post = {
          // ...this.query,
          account_period_s: account_period,
          account_period_e: account_period,
        }
    if(list.length) {
      post.account_period_s = list[list.length - 1].account_period
      post.account_period_e = list[0].account_period
    }
    wx.$post(3, 'Account/query_all_account_period', post).then(res => {
      if(res.errcode !== 0) return
      // let row = res.data.row[0],
      //     list = this.data.list
      // list[idx] = row
      // this.setData({
      //   list,
      // })

      let rows = res.data.row,
          obj = {}
      rows.forEach(row => obj[row.account_period] = row)
      list.forEach((item, i) => {
        list[i] = obj[item.account_period] || item
      })
      this.setData({
        list,
      })
    })
  },

  //230118 yan 取消使用v2接口，增加结转反结转时统计凭证、报表
  async carryForward(isCancel, post, idx){
    let period = post.account_period,
      {list} = this.data,rows;
    wx.showLoading({mask: true})
    if (isCancel){
      rows = list.filter(item => item.account_state !== '处理' && item.account_period >= period)
      for (let i = 0; i < rows.length; i++) {
        let period1 = rows[i].account_period,
          data = {is_overwrite: post.is_overwrite,account_period: period1}
        await this.carryOver(isCancel,data);
        await this.sumAccount(period,'voucher');
        await this.sumAccount(period,'account');
      }

    } else {
      rows = list.filter(item => item.account_state !== '完结' && item.account_period <= period);
      rows.sort((a, b) => { return a.account_period - b.account_period })//升序
      for (let i = 0; i < rows.length; i++) {
        let period2 = rows[i].account_period,
          data = {is_overwrite: post.is_overwrite,account_period: period2}
        await this.sumAccount(period,'voucher');
        await this.sumAccount(period,'account');
        await this.carryOver(isCancel,data);
      }
    }
    wx.$toast(isCancel ? '反结转成功！' : '结转成功！')
    // 成功后，重新请求该条数据
    this.getRowData(post.account_period, idx)
  },

  //统计凭证、报表
  sumAccount(period,type){
    return new Promise(resolve => {
      wx.$post(3,type === 'voucher' ? 'Voucher/sum_all_voucher': 'CustomAccount/update_auto_value', {"account_period": period}).then(res => {
        if (res.errcode != 0) return;
        resolve();
      });
    });
  },
  carryOver(isCancel,post){
    let url = isCancel ? 'Account/cancel_charges_all_account_summary' : 'Account/charges_all_account_summary';
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res=>{
        if(res.errcode !== 0) return
        resolve();
      })
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    this.ready()
    let { entity, } = options,
        auth = await wx.$getAuth(entity)
    this.data.auth = auth

    this.getDataList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
